<?php

namespace app\common\model\user;

use app\api\controller\Pub;
use app\common\model\power\Rolepower;
use think\Db;
use think\Model;

class User extends Model
{
    // 设置当前模型对应的完整数据表名称
    protected $table  = 'user';
    protected $pk     = 'UserId';
    const STATEINT    = 1;
    const STATEOK     = 1;
    const STATELOCK   = 2;
    const STATEDELETE = 3;

    const SEXINT = 1; //性别默认为男
    /**
     * 状态分类
     * @param  string $value [description]
     * @return [type]        [description]
     */
    public static function getStatusText($value = '')
    {
        $status = [-1 => '全部', 1 => '正常', 2 => '锁定'];
        if ($value !== '') {
            return $status[$value];
        }
        return $status;
    }

    /**
     * 根据power获得角色然后获取获得id
     * @return [type] [description]
     */
    public static function powercode_getuserid($power)
    {
        $data = Rolepower::where('PowerCode', $power)->value('RoleMap');
        return self::role_getuserid($data);
    }

    /**
     * 根据角色获取id
     * @return [type] [description]
     */
    public static function role_getuserid($Role)
    {
        switch ($Role) {
            case 'hawa':
                $Role = 101;
                break;
            case 'buss':
                $Role = 201;
                break;
            case 'ware':
                $Role = 202;
                break;
            case 'acco':
                $Role = 203;
                break;
            case 'manager':
                $Role = 204;
                break;
            case 'supermanager':
                $Role = 205;
                break;
        }
        return User::where('Role', 'in', $Role)->where('State', User::STATEOK)->column('UserId');
    }
    /**
     * 获取员工列表
     * @return [type] [description]
     */
    public static function get_stafflist(){
        $data = User::where('State','<>', User::STATEDELETE);
        $rolearr =  [201, 202, 203, 204, 205,206,207,208,106];
        $data = $data->where('Role', 'in',$rolearr);
        $data = $data->field('UserId,Iphone,Name,Role,State');
        $data = $data->order('Role desc');
        $data = $data->where('Iphone', '<>',15511313142);
        $data = $data->select();
        $rdata['list'] =  $data->toArray();
        $rdata['rolename'] = getrolename();
        $rdata['userstate'] = self::getStatusText();
        return $rdata;
    }

    /**
     * 用户创建用户
     * @param  [type] $iphone [description]
     * @param  [type] $role   [description]
     * @param  string $name   [description]
     * @return [type]         [description]
     */
    public static function user_lock($userid)
    {
        $user = User::where('UserId', $userid)->where('State', '<>', User::STATEDELETE)->find();
        if (empty($user)) {
            return moerr('没有找到此账号信息');
        }
        if($user->UserId==Pub::userid()){
            return moerr('不可以锁定本账号');
        }
        if($user->State == User::STATELOCK){
            $user->State = User::STATEINT;
            $user->Jwt = '';
            $user->save();
            return sok(['msg'=>'账号已经解除锁定','State'=>User::STATEINT]);
        }else{
            $user->State = User::STATELOCK;
            $user->Jwt = '';
            $user->save();
            return sok(['msg'=>'账号锁定成功，已经强制下线','State'=>User::STATELOCK]);
        }
    }

    /**
     * 获取财务报销的用户列表
     * @return [type] [description]
     */
    public static function getcostuserlist()
    {
        $data = User::where('State', User::STATEOK);
        $rolearr =  [201, 202, 203, 204, 205,206,208];
        //判断是否自营运输队
        if(PROPRIETARY_TRANSITCOMPANYUSER){
            $rolearr = array_merge([106,107],$rolearr);
        }
        $data = $data->where('Role', 'in',$rolearr);
        $data = $data->field('UserId,Iphone,Name,Role');
        $data = $data->order('Role desc');
        $data = $data->select();
        return $data->toArray();
    }
    /**
     * 账号是否已经登录
     * 若已登录直接返回userid，没有登录则返回错误
     * @param  [type]  $token [description]
     * @return boolean        [description]
     */
    public static function is_login($token)
    {
        if (empty($token)) {
            return serr('口令过期，请重新登录');
        }
        $userlogininfo = Pub::getuserid(input('token'));
        return $userlogininfo;
    }

    /**
     * 通过jwt判断账号是否已经登录
     * 若已登录直接返回userid，没有登录则返回错误
     * @param  [type]  $token [description]
     * @return boolean        [description]
     */
    public static function is_sessionlogin()
    {
        $token = input('token');
	    if (empty($token)) {
            return serr('口令过期，请重新登录');
        }
        $userlogininfo = Pub::getuserid(input('token'));
        return $userlogininfo;
    }

    /**
     * 获取信息
     * @param  [type] $id [description]
     * @return [type]     [description]
     */
    public static function getpublicinfo($id = '')
    {
        if (empty($id)) {
            return [];
        }
        $data = User::where('UserId', $id)->find();
        if (empty($data)) {
            $data['Iphone'] = '';
            $data['Name']   = '';
        } else if ($data['State'] == User::STATEDELETE) {
            $data = $data->visible(['Iphone', 'Name', 'Role'])->toArray();
            $data['Name'] = $data['Name'].'(已注销)';
        } else {
            $data = $data->visible(['Iphone', 'Name', 'Role'])->toArray();
        }
        $data['Role'] = getrolename($data['Role']);
        return $data;
    }

    /**
     * 获取信息
     * @param  [type] $id [description]
     * @return [type]     [description]
     */
    public static function getpubliclist($id = [])
    {
        if (empty($id)) {
            return [];
        }
        $data = User::where('UserId','in', $id)->select();
        $data = $data->visible(['Iphone', 'Name', 'Role','State','UserId'])->toArray();
        if (empty($data)) {
           return [];
        }
        foreach ($data as $key => $value) {
            if ($value['State'] == User::STATEDELETE) {
                $data[$key]['Name'] = $value['Name'].'(已注销)';
            }
            $data[$key]['Role'] = getrolename($value['Role']);
        }
        return $data;
    }


    /**
     * 获取信息
     * @param  [type] $id [description]
     * @return [type]     [description]
     */
    public static function getinfo($iphone = '', $id = '')
    {
        if (empty($iphone)) {
            if (empty($id)) {
                $userlogininfo = Pub::getuserid(input('token'));
                $userid        = $userlogininfo['msg'];
            } else {
                $userid = $id;
            }
            $data = User::where('UserId', $userid)->find();
        } else {
            $data = User::where('Iphone', $iphone)->where('state', '<>', User::STATEDELETE)->find();
        }
        // $data->hidden(['wechat_headimg','push_permission','UserId','sex','region']);
        return $data;
    }
    /**
     * 用户登录的逻辑判断user_login_state
     * @param  [type] $id [微信openid]
     * @return [type]     [用户uid]
     */
    public static function user_login_state($id)
    {
        $sb = User::where('UserId', $id)->find();
        if (empty($sb) || $sb['State'] == 3) {
            return serr('没找到您的账号');
        }
        if ($sb['State'] == 2) {
            return serr('账号被锁定');
        }
        return sok($sb['UserId']);
    }
    /**
     * 用手机号判断账号状态
     * @param  [type] $iphone [description]
     * @return [type]         [description]
     */
    public static function iphone_state($iphone)
    {
        $sb = User::where('Iphone', $iphone)->where('State', '<>', User::STATEDELETE)->find();
        if (empty($sb) || $sb['State'] == User::STATEDELETE) {
            return serr('此手机号没有绑定账户');
        }
        if ($sb['State'] == User::STATELOCK) {
            return serr('账号被锁定');
        }
        return sok($sb['UserId']);
    }

    /**
     * 判断是否存在此微信openid
     * @param  [type] $id [微信openid]
     * @return [type]     [用户uid]
     */
    public static function iswechatid($id,$model=false)
    {
        $data = User::where('WechatId', $id)->where('State', '<>', User::STATEDELETE)->find();
        if (empty($data)) {
            return serr();
        } else {
            if($model==false){
                return sok($data->UserId);
            }else{
                return sok($data);
            }
        }
    }

    /**
     * 判断是否存在此微信openid
     * @param  [type] $id [微信openid]
     * @return [type]     [用户uid]
     */
    public static function ismpwechatid($id)
    {
        $data = User::where('MpWechatId', $id)->where('State', '<>', User::STATEDELETE)->find();
        if (empty($data)) {
            return serr();
        } else {
            return sok($data->UserId);
        }
    }

    /**
     * 用户创建用户
     * @param  [type] $iphone [description]
     * @param  [type] $role   [description]
     * @param  string $name   [description]
     * @return [type]         [description]
     */
    public static function user_createuser($iphone, $role, $name = '')
    {
        $sb = User::where('Iphone', $iphone)->where('State', '<>', User::STATEDELETE)->find();
        if (!empty($sb) && $role !== $sb['Role']) {
            return moerr('账号系统中已存在此手机号，无法创建');
        }

        $user         = new User;
        $user->Iphone = $iphone;
        $user->Role   = $role;
        if (empty($name)) {
            $user->Name = '未定义';
        } else {
            $user->Name = $name;
        }
        $user->State = User::STATEINT;
        $user->Sex   = User::SEXINT;
        $user->save();
        return $user->UserId;
    }

    /**
     * 创建用户，如果id已存在则返回此id
     * @param  [type] $WechatId [description]
     * @return [type]                [description]
     */
    public static function adduser($WechatId)
    {
        if (!self::iswechatid($WechatId)['code']) {
            $user           = new User;
            $user->WechatId = $WechatId;
            $user->Role     = 101;
            $user->State    = User::STATEINT;
            $user->Sex      = User::SEXINT;
            $user->save();
            return sok($user->UserId);
        } else {
            return serr('账号已存在，请勿重新创建');
        }
    }

    /**
     * 创建用户，如果id已存在则返回此id
     * @param  [type] $WechatId [description]
     * @return [type]                [description]
     */
    public static function mp_wechat_adduser($WechatId)
    {
        if (!self::ismpwechatid($WechatId)['code']) {
            $user             = new User;
            $user->MpWechatId = $WechatId;
            $user->Role       = 101;
            $user->State      = User::STATEINT;
            $user->Sex        = User::SEXINT;
            $user->save();
            return sok($user->UserId);
        } else {
            return serr('账号已存在，请勿重新创建');
        }
    }

    /**
     * 获取用户wechatopenid
     * @return [type] [description]
     */
    public static function getWechatId($id)
    {
        $data = User::where('UserId', $id)->where('State', '<>', User::STATEDELETE)->find();
        if (empty($data['WechatId'])) {
            return [];
        }
        return $data['WechatId'];
    }

    /**
     * 获取用户wechatopenid
     * @return [type] [description]
     */
    public static function getWechatIdlist($id)
    {
        $data = User::where('UserId', 'in', $id)->where('State', '<>', User::STATEDELETE)->column('WechatId');
        foreach ($data as $key => $value) {
            if (empty($value)) {
                unset($data[$key]);
            }
        }
        $data = array_values($data);
        if (empty($data)) {
            return [];
        }
        return $data;
    }

    /**
     * 获取库管wechatopenid
     * @return [type] [description]
     */
    public static function getwarehouseWechatId()
    {
        $data = User::where('Role', 2)->where('State', '<>', User::STATEDELETE)->select();
        foreach ($data as $key => $value) {
            $idarray[$key] = $value['WechatId'];
        }

        if (empty($idarray)) {
            return [];
        }
        return $idarray;
    }

    /**
     * 获取超级管理员wechatopenid
     * @return [type] [description]
     */
    public static function getsupermanagerWechatId()
    {
        $data = User::where('Role', 9)->select();
        foreach ($data as $key => $value) {
            $idarray[$key] = $value['WechatId'];
        }
        if (empty($idarray)) {
            return [];
        }
        return $idarray;
    }

    /**
     * 获取用户数量
     * @return [type] [description]
     */
    public static function getusercount()
    {
        $count = Db::table('user')->count();
        return $count + USERFALSECOUNT;
    }

    /**
     * 查询用户信息
     *
     */
    public function getUserList($where)
    {
        $data = User::where($where)->visible(['UserId','Role','Name'])->select();
        return $data;
    }
}
